package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

const (
	baseurl = "http://inputtools.google.com/request"
	lang    = "ja-t-i0-und"
	params  = "&cp=0&cs=1&ie=utf-8&oe=utf-8&app=jinput"
)

func suggest(s string) []string {
	if len(s) == 0 {
		return []string{}
	}

	url := fmt.Sprintf(baseurl+"?text=%s&itc=%s&num=%d"+params, s, lang, len(s))
	res, err := http.Get(url)
	die(err, "error making HTTP request")

	body, err := ioutil.ReadAll(res.Body)
	die(err)

	var output []interface{}
	err = json.Unmarshal(body, &output)
	die(err, "error unmarshaling JSON")

	// slog through the JSON object they give us
	tmp1 := output[1].([]interface{})
	tmp2 := tmp1[0].([]interface{})
	tmp3 := tmp2[1].([]interface{})
	suggestions := make([]string, len(tmp3))
	for i := range tmp3 {
		suggestions[i] = tmp3[i].(string)
	}

	return suggestions
}
